package com.example.tongyao.system.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

/**
 * web前端跨域和swagger2配置类
 * web接口列表访问地址：http://localhost:8081/swagger-ui.html
 *
 * @version 1.0
 * @author tongyao
 * @since 2020-06-13
 */
@Configuration
public class CorsConfig extends WebMvcConfigurationSupport {
	
	/**
     * Swagger Config
     */
    Boolean swaggerEnabled = true;
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                // 是否开启
                .enable(swaggerEnabled)//true
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.tongyao"))
                .paths(PathSelectors.any())
                .build();
    }
    
	private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title("Tong Yao")
                //创建人
                .contact(new Contact("zhang-tongyao", null, "super_tongyao@163.com"))
                //版本号
                .version("2.2.6")
                //描述
                .description("基于springboot 2.2.6 + shiro 1.4.0 + MybatisPlus 3.1.1 打造的纯后台权限框架。请尊重保留作者注释及相关信息。")
                .build();
    }
	
	@Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }
	
	/**
	 *  web前端报错 Access-Control-Allow-Origin 的前端问题解决
	 */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH")
                .allowCredentials(true).maxAge(3600);
    }
}